package com.machine.filling.util;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.machine.filling.R;


public class CustomToast {
	private static String oldMsg;
	private static Toast toast = null;
	private static long oneTime = 0;
	private static long twoTime = 0;
	private static TextView textView = null;
	public static void showToast(Context context, String s){
		if(toast == null){
			toast = showCustomToast(context, s);
			toast.show();
			oneTime = System.currentTimeMillis();
			oldMsg = s;
		}else {
			twoTime = System.currentTimeMillis();
			if(s.equals(oldMsg)){
				if(twoTime - oneTime > Toast.LENGTH_SHORT){
					toast.show();
				}
			}else {
				oldMsg = s;
				View view = toast.getView();
				if(textView == null){
					textView = ((TextView) view.findViewById(R.id.toast_text));
				}
				textView.setText(s);
				toast.show();
			}
		}
		oneTime = twoTime;
	}
	
	public static void showToast(Context context, int resId){
		showToast(context, context.getString(resId)); 
	}
	
	private static Toast showCustomToast(Context context, String text) {
		View toastRoot = LayoutInflater.from(context).inflate(
				R.layout.common_toast, null);
		((TextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(context);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		return toast;
	}
	
	public static void destroy(){
		toast = null;
		textView = null;
	}
}
